const { addressApi } = require('../../../utils/api/index.js')
Page({
  data: {
    id: null, // 地址ID，编辑时传入
    loading: false,
    showPicker: false,
    form: {
      name: '',
      phone: '',
      province: '',
      city: '',
      region: '',
      regionText:'',
      detailAddress: '',
      latitude: null,
      longitude: null,
      isDefault: false
    }
  },

  onLoad(options) {
    if (options.id) {
      // 编辑模式，获取地址详情
      this.setData({ id: options.id });
      this.getAddressDetail(options.id);
    }
  },

  // 获取地址详情
  async getAddressDetail(id) {
    try {
      const param = {
        addressId: id
      }
      const result = await addressApi.queryAddressDetail(param);
      if (result.code === '0000') {
        const address = result.data;
        this.setData({
          form: {
            name: address.name,
            phone: address.phone,
            province: address.province,
            city: address.city,
            region: address.region,
            regionText: `${address.province} ${address.city} ${address.region}`,
            detailAddress: address.detailAddress,
            latitude: address.latitude,
            longitude: address.longitude,
            isDefault: address.isDefault
          }
        });
      }else{
        wx.showToast({
          title: '查询收货地址失败：'+ result.msg,
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('查询收货地址失败：', error)
      wx.showToast({
        title: '查询收货地址失败',
        icon: 'none'
      })
    }
  },

  // 表单字段变化
  onNameChange(e) {
    this.setData({
      'form.name': e.detail.value
    });
  },

  onMobileChange(e) {
    this.setData({
      'form.phone': e.detail.value
    });
  },

  onAddressChange(e) {
    this.setData({
      'form.detailAddress': e.detail.value
    });
  },

  // 默认地址切换
  onDefaultChange(e) {
    this.setData({
      'form.isDefault': e.detail.value
    });
  },

  // 显示省市区选择器
  showRegionPicker() {
    this.setData({ showPicker: true });
  },

  // 隐藏省市区选择器
  hideRegionPicker() {
    this.setData({ showPicker: false });
  },

  // 地图选点
  chooseLocation() {
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => this.userChooseLocation(),
            fail: () => this.showAuthTip()
          });
        } else {
          this.userChooseLocation();
        }
      }
    });
  },
  
  userChooseLocation() {
    wx.chooseLocation({
      success: (res) => {
        if (res.name && res.address) {
          this.setData({
            'form.latitude': res.latitude,
            'form.longitude': res.longitude
          });
          // 自动解析地址中的省市区
          this.reverseGeocoder(res.latitude,res.longitude);
        }
      }
    });
  },

  // 显示权限提示
  showAuthTip() {
    wx.showModal({
      title: '提示',
      content: '需要获取您的地理位置权限，请前往设置开启',
      confirmText: '去设置',
      success: (res) => {
        if (res.confirm) {
          wx.openSetting();
        }
      }
    });
  },

  // 获取当前位置
  getCurrentLocation() {
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => this._getLocationDetail(),
            fail: () => this.showAuthTip()
          });
        } else {
          this._getLocationDetail();
        }
      }
    });
  },

  // 获取详细位置信息
  _getLocationDetail() {
    wx.showLoading({ title: '定位中...' });
    
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.reverseGeocoder(res.latitude, res.longitude);
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({ title: '定位失败', icon: 'none' });
      }
    });
  },

  // 逆地理编码（坐标转地址）
  reverseGeocoder(latitude, longitude) {
    //TODO 腾讯的key从后端获取，并存储到wx.setStorageSync('key', data)
    wx.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=3JABZ-HQHYW-ZBERN-36SIR-PC2W3-ZPFLX`,
      success: (res) => {
        wx.hideLoading();
        if (res.data.status === 0) {
          const address = res.data.result;
          this.setData({
            'form.latitude': latitude,
            'form.longitude': longitude,
            'form.province': address.address_component.province,
            'form.city': address.address_component.city,
            'form.region': address.address_component.district,
            'form.regionText': `${address.address_component.province} ${address.address_component.city} ${address.address_component.district}`,
            'form.detailAddress': address.address_component.street + address.address_component.street_number
          });
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      },
      fail: (res) => {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
      }

    });
  },

  // 提交表单
  async submitForm() {
    if (!this.validateForm()) return;
    
    this.setData({ loading: true });
    
    const { id, form } = this.data;
    const params = {
      addressId: id,
      userId: '1837425962481504256',
      name: form.name,
      phone: form.phone,
      province: form.province,
      city: form.city,
      region: form.region,
      detailAddress: form.detailAddress,
      latitude: form.latitude,
      longitude: form.longitude,
      isDefault: form.isDefault
    };
    if(id != null && id != ''){
      //编辑
      try{
        const result = await addressApi.updateDeliveryAddress(params);
        if (result.code === '0000') {
          wx.showToast({
            title: '修改收货地址成功',
            icon: 'none'
          })
        }else{
          wx.showToast({
            title: '修改收货地址失败：'+ result.msg,
            icon: 'none'
          })
        }
      }catch (error) {
        console.error('修改收货地址失败：', error)
        wx.showToast({
          title: '修改收货地址失败',
          icon: 'none'
        })
      }
    }else{
      //新增
      try{
        const result = await addressApi.saveDeliveryAddress(params);
        if (result.code === '0000') {
          wx.showToast({
            title: '新增收货地址成功',
            icon: 'none'
          })
        }else{
          wx.showToast({
            title: '新增收货地址失败：'+ result.msg,
            icon: 'none'
          })
        }
      }catch (error) {
        console.error('新增收货地址失败：', error)
        wx.showToast({
          title: '修改收货地址失败',
          icon: 'none'
        })
      }
    }
    this.setData({ loading: false });
  },

  // 表单验证
  validateForm() {
    const { name, phone, province, detailAddress } = this.data.form;
    
    if (!name) {
      wx.showToast({ title: '请输入收货人姓名', icon: 'none' });
      return false;
    }
    
    if (!phone) {
      wx.showToast({ title: '请输入手机号码', icon: 'none' });
      return false;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({ title: '请输入正确的手机号码', icon: 'none' });
      return false;
    }
    
    if (!province) {
      wx.showToast({ title: '请选择所在地区', icon: 'none' });
      return false;
    }
    
    if (!detailAddress) {
      wx.showToast({ title: '请输入详细地址', icon: 'none' });
      return false;
    }
    
    return true;
  },

  // 显示权限提示
  showAuthTip() {
    wx.showModal({
      title: '提示',
      content: '需要获取您的地理位置权限，请前往设置开启',
      confirmText: '去设置',
      success: (res) => {
        if (res.confirm) {
          wx.openSetting();
        }
      }
    });
  }
});